package UDP;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

/**
 * Created with Intellij IDEA.
 * Description;
 * User:墨琦
 * Data:2023-09-06
 * Time:14:50
 */
//客户端
public class UdpEchoClint {
    private DatagramSocket socket=null;
    private String serverIP;
    private int serverPort;
    public UdpEchoClint(String ip,int port) throws SocketException {
        socket=new DatagramSocket();
        serverIP=ip;
        serverPort=port;
    }
    public void start() throws IOException
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("客户端1启动：");
        while(true){
            //发送内容
            System.out.print("输入内容：");
            String str1=sc.next();
            DatagramPacket t1=new DatagramPacket(str1.getBytes(),str1.getBytes().length, InetAddress.getByName(serverIP),serverPort);
            socket.send(t1);
            //返回收到的内容
            DatagramPacket t2=new DatagramPacket(new byte[100],100);
            socket.receive(t2);
            String str2=new String(t2.getData(),0,t2.getLength());
            System.out.println("回应："+str2);
        }

    }

    public static void main(String[] args) throws IOException {
            UdpEchoClint udpEchoClint=new UdpEchoClint("127.0.0.1",9090);
            udpEchoClint.start();
    }
}
